package top.songxs.gmall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import top.songxs.gmall.common.constant.GmallCacheConstant;
import top.songxs.gmall.common.execption.GmallException;
import top.songxs.gmall.common.result.ResultCodeEnum;
import top.songxs.gmall.user.dto.UserLoginDTO;
import top.songxs.gmall.user.entity.UserInfo;
import top.songxs.gmall.user.service.UserInfoService;
import top.songxs.gmall.user.mapper.UserInfoMapper;
import org.springframework.stereotype.Service;
import top.songxs.gmall.user.vo.UserLoginSuccessVo;

import java.util.UUID;

/**
* @author 86176
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2023-05-30 18:32:08
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public UserLoginSuccessVo login(UserLoginDTO userLoginDTO) {

        // 根据用户名查询从数据库中查询用户数据
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getLoginName,userLoginDTO.getLoginName());
        UserInfo userInfo = this.getOne(wrapper);
        // 判断userInfo是否存在
        if (userInfo==null){
            throw new GmallException(ResultCodeEnum.LOGIN_AUTH);
        }
        // 判断密码
        String loginPasswd = DigestUtils.md5DigestAsHex(userLoginDTO.getPasswd().getBytes());
        if (!loginPasswd.equalsIgnoreCase(userInfo.getPasswd())){
            throw new GmallException(ResultCodeEnum.LOGIN_AUTH);
        }

        // 生成token
        String token = UUID.randomUUID().toString().replace("-", "");

        // 将用户数据存储到Redis中
        redisTemplate.opsForValue().set(GmallCacheConstant.REDIS_USER_INFO+token, JSON.toJSONString(userInfo));
        // 封装结果数据进行返回
        UserLoginSuccessVo userLoginSuccessVo = new UserLoginSuccessVo();
        userLoginSuccessVo.setToken(token);
        userLoginSuccessVo.setNickName(userInfo.getNickName());

        // 返回
        return userLoginSuccessVo;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(GmallCacheConstant.REDIS_USER_INFO+token);
    }
}




